const qiniuUploader = require("../../../utils/qiniuUploader");
// import Auther from "./../../utils/auther.js"
// var auther = new Auther();
// var api = require('../../config/api.js');

function initQiniu() {
  console.log("pages, ", Page)
  let token = app.globalData.uptoken
  var myDate = new Date(); 
  console.log("init", token)
    var options = {
      region: 'ECN', // 华东
      uptoken: token, //七牛token
      fileHead: myDate.getTime(),
      method: "POST"
    };
    qiniuUploader.init(options);


};

var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user:"",
    uploadData:{
      images:[]
    },
    foodsLists:[

    ],
    images: [],
    dosing_img: [],
    title:"",
    des:"",
    diff:0,
    cookTime: 0,
    images: [],
    type:0,
    token: "",
    img_len: 0,
    typeArr:[
      {
        label:"家常菜",
        value:"9"
      },
      {
        label: "家庭宴席",
        value: "10"
      },
      {
        label: "颜值",
        value: "11"
      },
      {
        label: "素菜",
        value: "12"
      },
      {
        label: "川菜",
        value: "13"
      },
      {
        label: "鲁菜",
        value: "14"
      },
      {
        label: "粤菜",
        value: "15"
      },
      {
        label: "湘菜",
        value: "16"
      },
      {
        label: "西餐",
        value: "17"
      }
    ],
    stepsLists:[],
    status: 'add'
  },

  chooseImage(e) {
    console.log("choose")
    wx.chooseImage({
      sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        const images = this.data.dosing_img.concat(res.tempFilePaths)
        // 限制最多只能留下3张照片

        const images1 = images
        console.log(images)
        this.setData({
          dosing_img: images1
        })
      }
    })
  },
  removeImage(e) {
    console.log("remove")
    var that = this;
    var images = that.data.dosing_img;
    // 获取要删除的第几张图片的下标
    const idx = e.currentTarget.dataset.idx
    // splice  第一个参数是下表值  第二个参数是删除的数量
    images.splice(idx,1)
    this.setData({
      dosing_img: images
    })
  },
 
  handleImagePreview(e) {
    const idx = e.target.dataset.idx
    const images = this.data.dosing_img
    wx.previewImage({
      current: images[idx],  //当前预览的图片
      urls: images,  //所有要预览的图片
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var myDate = new Date(); 
    console.log("times",myDate.getTime())
    if (!wx.getStorageSync('user_id')){
      that.setData({
        T_F: "none"
      })
      wx.showToast({
        title: '请先登录',
        icon: "none"
      })
      return false
    }
    //七牛初始化
    wx.request({
      url: 'http://" + app.globalData.url + "/user/get_qiniu/',
      data:{"user_id": app.globalData.user_id},
      success: function (res) {
        // 设置token
        that.data.token = res.data.token
        app.globalData.uptoken = res.data.token
      }
    })
    
  },
  //获取详情 
  getDetail(id) {
    let that = this;

    wx.request({
      url: api.getFood,
      data: {
        id
      },
      success: function (res) {
        let data = res.data.data;
        data.images = data.images.split(",");
        
        that.data.typeArr.forEach((v,i,arr)=>{
          if(v.value == data.type){
            data.type = i;
          }
        })

        that.data.diffArr.forEach((v, i, arr) => {
          if (v.value == data.diff) {
            data.diff = i;
          }
        })

        that.data.cookTimeArr.forEach((v, i, arr) => {
          if (v.value == data.cookTime) {
            data.cookTime = i;
          }
        });

        data.steps.forEach((v,i,arr)=>{
          v.name = v.content
        });
        
        that.setData({
          id:data.id,
          title:data.title,
          des:data.des,
          images: data.images,
          diff:data.diff,
          cookTime:data.cookTime,
          type:data.type,
          uploadData: {images:data.images},
          foodsLists: data.food_lists,
          stepsLists: data.steps,
          status: 'edit'
        })
      }
    })
  },
  onReady: function () {

  },
  onShow: function () {
    
  },
  //上传图片
  uploadImgs(e) {
    let that = this;
    let { uploadData } = that.data;
    var pics = this.data;
    console.log(pics)
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(resFile) {

        const filePath = resFile.tempFiles[0];
        console.log("file", resFile)
        qiniuUploader.upload(filePath.path, (res) => {
          if( uploadData.images.length == 6 ){
            wx.showToast({
              title: '只能上传6张图片!',
              icon: "none"
            });
            return false;
          }

          uploadData.images.push(res.imageURL);

          that.setData({
            uploadData: uploadData
          });

        }, (error) => {
          console.error('error: ' + JSON.stringify(error));
        });
      }
    })
  },
  //删除图片
  deleteImg(e){
    let that = this;
    let { uploadData } = this.data;
    let src = e.currentTarget.dataset.src;

    uploadData.images.forEach((v, i, arr) => {
      if (v == src) {
        uploadData.images.splice(i, 1);
      }
    });

    that.setData({
      uploadData: uploadData
    });
  },
  //类型改变
  typeChange(e){
    let val = e.detail.value;
    this.setData({
      type: parseInt(val)
    })
  },
  formSubmit(e){
    let that = this;
    let status = that.data.status;
    let data = e.detail.value;
    let { uploadData, diff, cookTime, type,diffArr,cookTimeArr,typeArr,foodsLists,stepsLists } = this.data;
    console.log(status, e)
    if (that.data.dosing_img.length == 0) {
      wx.showToast({
        title: '最少上传一张图片!',
        icon: "none"
      });
      
      return false;
    }else if(data.title == ""){
      wx.showToast({
        title: '请输入标题!',
        icon: "none"
      });

      return false;
    }else if (foodsLists.length != 0){
      let isTrue = true;
      let message = "";
      foodsLists.forEach((v, i, arr) => {
        if (data['name'+i] == "") {

          isTrue = false;
          message = '食材名称不能为空!';
          return false

        } else if (data['attr'+i] == ""){

          isTrue = false;
          message = '食材属性不能为空!';
          return false

        }
      });

      if (!isTrue){
        wx.showToast({
          title: message,
          icon: "none"
        });

        return false;
      }
    } else if (stepsLists.length != 0) {
      let isTrue = true;
      let message = "";
      stepsLists.forEach((v, i, arr) => {
        if (data['step' + i] == "") {

          isTrue = false;
          message = '步骤内容不能为空!';
          return false

        }
      });

      if (!isTrue) {
        wx.showToast({
          title: message,
          icon: "none"
        });

        return false;
      }
    }
    let reqData = {
      title: data.title,
      images: that.data.images,
      type: typeArr[parseInt(type)].value,
      userid: that.data.user.id,
      lists: [],
      steps: []
    };
    console.log("reqdata", reqData)
    let lists = [];
    if(foodsLists.length != 0){
      foodsLists.forEach((v,i,arr)=>{
        let obj = {};
        if(status == 'add'){
          obj = {
            name: data['name' + i],
            attr: data['attr' + i],
          }
        }else if(status == 'edit'){
          obj = {
            id: v.id,
            name: data['name' + i],
            attr: data['attr' + i],
          }
        }
        lists.push(obj);
      });
      
      reqData.lists = lists;
    }

    let steps = [];
    if (stepsLists.length != 0) {
      stepsLists.forEach((v, i, arr) => {
        let obj = {};
        if (status == 'add') {
          obj = {
            name: data['step' + i]
          }
        } else if (status == 'edit') {
          obj = {
            id: v.id,
            name: data['step' + i]
          }
        }
        steps.push(obj);
      });

      reqData.steps = steps;
    }
   
    console.log("list, steps", reqData.lists, reqData.steps)
    if (reqData.lists.length == 0){
      console.log("aaabbbccclist")
      wx.showToast({
        title: '请输入食材清单数据，最少也要有一种食材',
        icon: "none"
      })
      return false
    }
    if (reqData.steps.length == 0){
      wx.showToast({
        title: '请输入步骤，最少也要有一步',
        icon: "none"
      })
      return false
    }
    if(status == "add"){
      let token = that.data.token
      if (that.data.img_len<that.data.dosing_img.length){
        for (let index = 0; index < this.data.dosing_img.length; index++) {
          wx.uploadFile({
            url: 'https://upload-z0.qiniup.com',
            name: 'file',
            filePath: that.data.dosing_img[0],
            header: {
              "Content-Type": "multipart/form-data"
            },
           formData: {
             token: token,
           },
           success: function(res) {
  
             that.data.img_len+= 1;
             if (res.statusCode == 200){
              that.data.images.push(res.data)
            
             }
             console.log("aabbccdd", that.data.img_len, that.data.dosing_img.length, that.data.images)
             if (that.data.img_len == that.data.dosing_img.length){
               reqData.images = that.data.images
              reqData.user_id = app.globalData.user_id
                      wx.request({
                url: "http://" + app.globalData.url + "/user/addcook/",
                data: reqData,
                method: 'POST',
                success: function (res) {
                  console.log("aabbccdd")
                  wx.showToast({
                    title: res.data.msg,
                    icon: "none"
                  })
                  wx.switchTab({
                    url: '../../../pages/my/publish/publish',
                  })
                }
              })
             }
           },
         });
        }
      }else{
        wx.showToast({
          title: '正在上传菜谱，请勿重复点击',
          icon: "none"
        })
      }
 

    }
    
  },
  //添加食材
  addFoodLists(){
    let foodsLists = this.data.foodsLists;
        foodsLists.push({
          name:"",
          attr:""
        });
    this.setData({
      foodsLists:foodsLists
    })
  },
  //修改食材名称
  getFoodName(e){
    let index = e.currentTarget.dataset.index;
    let name = e.detail.value;
    let foodsLists = this.data.foodsLists;
        foodsLists.forEach((v, i, arr) => {
          if (i == index) {
            v.name = name;
          }
        });

    this.setData({
      foodsLists:foodsLists
    })
  },
  //修改食材属性
  getFoodAttr(e) {
    let index = e.currentTarget.dataset.index;
    let attr = e.detail.value;
    let foodsLists = this.data.foodsLists;
    foodsLists.forEach((v, i, arr) => {
      if (i == index) {
        v.attr = attr;
      }
    });

    this.setData({
      foodsLists: foodsLists
    })
  },
  //删除食材
  delLists(e){
    let index = e.currentTarget.dataset.index;
    let foodsLists = this.data.foodsLists;
        foodsLists.forEach((v,i,arr)=>{
          if(i == index){
            foodsLists.splice(i,1);
          }
        });
    this.setData({
      foodsLists:foodsLists
    })
  },
  //步骤
  addSteps(){
    let stepsLists = this.data.stepsLists;
        stepsLists.push({
          name:""
        });
    this.setData({
      stepsLists: stepsLists
    });
  },
  //修改食材属性
  getStepName(e) {
    let index = e.currentTarget.dataset.index;
    let name = e.detail.value;
    let stepsLists = this.data.stepsLists;
    stepsLists.forEach((v, i, arr) => {
      if (i == index) {
        v.name = name;
      }
    });

    this.setData({
      stepsLists: stepsLists
    })
  },
  //删除步骤
  delSteps(e){
    let index = e.currentTarget.dataset.index;
    let stepsLists = this.data.stepsLists;
    stepsLists.forEach((v, i, arr) => {
      if (i == index) {
        stepsLists.splice(i, 1);
      }
    });

    this.setData({
      stepsLists: stepsLists
    })
  },
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
